package book;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * @author：涂有
 * @date 2017年3月1日 下午3:19:38
 */
public class ReentrantReadWriteLockTest2 {

	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	public void read(){
		
		lock.readLock().lock();
		try{
			System.out.println("获得读锁：" + Thread.currentThread().getName());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}finally{
			System.out.println("释放读锁：" + Thread.currentThread().getName());
			lock.readLock().unlock();
		}
	}
	public void write(){
		
		lock.writeLock().lock();
		try{
			System.out.println("获得写锁：" + Thread.currentThread().getName());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}finally{
			System.out.println("释放写锁：" + Thread.currentThread().getName());
			lock.writeLock().unlock();
		}
	}
	
	static class Read extends Thread{
		
		ReentrantReadWriteLockTest2 obj;
		
		public Read(ReentrantReadWriteLockTest2 obj){
			
			this.obj = obj;
		}
		
		@Override
		public void run() {
			obj.read();
		}
	}
	
	static class Write extends Thread{
		
		ReentrantReadWriteLockTest2 obj;
		
		public Write(ReentrantReadWriteLockTest2 obj){
			
			this.obj = obj;
		}
		
		@Override
		public void run() {
			obj.write();
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		
		final ReentrantReadWriteLockTest2 test = new ReentrantReadWriteLockTest2();
		Read read = new Read(test);
		Write write = new Write(test);
		
		//测试读写互斥
//		read.start();
//		write.start();
		
		//测试写读互斥
		write.start();
		read.start();
	}
}
